package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.sky.constant.OrdersConstant.*;
import static com.sky.constant.WebSocketConstant.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        // 1.处理各种业务异常(地址簿为空、 购物车数据为空)
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);

        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.getItem(shoppingCart);
        if(shoppingCarts == null || shoppingCarts.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 2.向订单表插入1条数据

        String detailAddress = addressBook.getProvinceName() + addressBook.getCityName()
                + addressBook.getDistrictName() + addressBook.getDetail();

        String number = UUID.randomUUID().toString().replace("-", "");

        Orders orders = Orders.builder()
                .number(number)
                .status(ORDERS_STATUS_OBLIGATION)
                .userId(userId)
                .orderTime(LocalDateTime.now())
                .payStatus(PAY_STATUS_UNPAID)
                .phone(addressBook.getPhone())
                .consignee(addressBook.getConsignee())
                .address(detailAddress)
                .build();

        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orderMapper.submit(orders);

        // 3.向订单明细表插入n条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart: shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBtch(orderDetailList);

        // 4.清空当前用户的购物车数据
        shoppingCartMapper.delete(ShoppingCart.builder().userId(BaseContext.getCurrentId()).build());

        // 5.封装VO返回结果

        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderTime(orders.getOrderTime());

        return orderSubmitVO;
    }

    /**
     * 模拟订单支付
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public LocalDateTime payment(OrdersPaymentDTO ordersPaymentDTO) {

        Orders orders = Orders.builder()
                            .number(ordersPaymentDTO.getOrderNumber())
                            .payMethod(ordersPaymentDTO.getPayMethod())
                            .status(ORDERS_STATUS_PENDING)
                            .payStatus(PAY_STATUS_PAID)
                            .build();

        orderMapper.update(orders);
        // 通过websocket项客户端浏览器推送消息 type orderId， content
        Map map = new HashMap();
        map.put(TYPE, TYPE_RECEIVED);
        map.put(ORDER_ID, orders.getId());
        map.put(CONTENT, CONTENT_VALUE + orders.getNumber());

        String json = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(json);
        return orders.getEstimatedDeliveryTime();

    }

    /**
     * 根据订单查询id
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {
        // 查询订单信息
        Orders orders = orderMapper.getById(id);

        // 查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getListByOrderId(id);
        OrderVO orderVO = new OrderVO();

        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 分页查询历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        int page = ordersPageQueryDTO.getPage();
        int pageSize = ordersPageQueryDTO.getPageSize();

        PageHelper.startPage(page, pageSize);
        List<Orders> orders = orderMapper.getList(ordersPageQueryDTO);

        List<OrderVO> orderVOS = new ArrayList<>();
        for (Orders ord : orders) {
            List<OrderDetail> orderDetails = orderDetailMapper.getListByOrderId(ord.getId());
            // 获取订单详情中所有菜品的名称并转为字符串
            String orderDishes = orderDetails.stream().map(OrderDetail::getName).collect(Collectors.joining(","));
            OrderVO orderVO = new OrderVO();
            orderVO.setOrderDetailList(orderDetails);
            BeanUtils.copyProperties(ord, orderVO);
            orderVO.setOrderDishes(orderDishes);
            orderVOS.add(orderVO);
        }
        PageInfo<OrderVO> pageInfo = new PageInfo<>(orderVOS);

        long total = pageInfo.getTotal();
        List<OrderVO> list = pageInfo.getList();

        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setRecords(list);

        return pageResult;
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = Orders.builder()
                                .id(ordersCancelDTO.getId())
                                .status(ORDERS_STATUS_CANCELED)
                                .cancelTime(LocalDateTime.now())
                                .cancelReason(ordersCancelDTO.getCancelReason())
                                .payStatus(PAY_STATUS_REFUND)
                                .build();

        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Transactional
    @Override
    public OrderSubmitVO repetition(Long id) {
        // 根据旧订单创建新订单，需要修改一些参数
        Orders orders = orderMapper.getById(id);
        orders.setStatus(ORDERS_STATUS_OBLIGATION);
        orders.setPayStatus(PAY_STATUS_UNPAID);
        orders.setPayMethod(null);
        orders.setCancelTime(null);
        orders.setNumber(UUID.randomUUID().toString().replace("-", ""));
        orders.setOrderTime(LocalDateTime.now());
        // 创建新订单
        orders.setId(null);
        orderMapper.submit(orders);

        // 创建新订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.getListByOrderId(id);
        for (OrderDetail orderdetail : orderDetails) {
            orderdetail.setOrderId(orders.getId());
            orderdetail.setId(null);
        }
        orderDetailMapper.insertBtch(orderDetails);

        // 返回VO对象
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderTime(orders.getOrderTime());

        return orderSubmitVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                                .id(ordersConfirmDTO.getId())
                                .status(ORDERS_STATUS_RECEIVED)
                                .checkoutTime(LocalDateTime.now())
                                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param rejectionDTO
     */
    @Override
    public void reject(OrdersRejectionDTO rejectionDTO) {
        Orders orders = Orders.builder()
                                .id(rejectionDTO.getId())
                                .rejectionReason(rejectionDTO.getRejectionReason())
                                .cancelTime(LocalDateTime.now())
                                .status(ORDERS_STATUS_REFUND)
                                .payStatus(PAY_STATUS_REFUND)
                                .build();

        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = Orders.builder()
                                .id(id)
                                .status(ORDERS_STATUS_DELIVERY)
                                .build();

        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = Orders.builder()
                                .id(id)
                                .status(ORDERS_STATUS_COMPLETED)
                                .deliveryTime(LocalDateTime.now())
                                .build();

        orderMapper.update(orders);
    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);

        // 通过websocket项客户端浏览器推送消息 type orderId， content
        Map map = new HashMap();
        map.put(TYPE, TYPE_REMINDER);
        map.put(ORDER_ID, orders.getId());
        map.put(CONTENT, CONTENT_VALUE + orders.getNumber());

        String json = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(json);
    }

    /**
     * 统计各个状态订单数数量
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Map map = new HashMap();
        map.put("status", ORDERS_STATUS_RECEIVED);
        Integer confirmed = orderMapper.statistics(map);
        map.put("status", ORDERS_STATUS_DELIVERY);
        Integer deliveryInProgress = orderMapper.statistics(map);
        map.put("status", ORDERS_STATUS_PENDING);
        Integer toBeConfirmed = orderMapper.statistics(map);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        return orderStatisticsVO;
    }
}
